{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import json\n",
    "import demjson"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "http://www.baidu.com 的短链接是： https://4m.cn/ctck6\n"
     ]
    }
   ],
   "source": [
    "# 长链接转短链接\n",
    "url = 'https://4m.cn/shorten'\n",
    "raw_url = 'http://www.baidu.com'\n",
    "data = {'url':raw_url}\n",
    "response = requests.post(url,data=data)\n",
    "\n",
    "if response.status_code != 200:\n",
    "    print(f'{data} 没有转换成功！！')\n",
    "else:\n",
    "    response.encoding='utf-8'\n",
    "    json_data = json.loads(response.text)\n",
    "    # json_data = demjson.decode(response.text)\n",
    "    short_url = json_data['short']\n",
    "    print(f'{raw_url} 的短链接是： {short_url}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://4m.cn/ctck6 的长链接是： http://www.baidu.com\n"
     ]
    }
   ],
   "source": [
    "# 短链接转长链接\n",
    "response = requests.head(short_url)\n",
    "long_url = response.headers.get('location')\n",
    "print(f'{short_url} 的长链接是： {long_url}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
